package com.base.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * xml工具类
 *
 * @author cjq on 2019/01/17
 */
public class XmlUtil {
    /**
     * 日志打印
     */
    private static final Logger logger = LoggerFactory.getLogger(XmlUtil.class);

    private static final String DEFAULT_CHARSET = "UTF-8";

    /**
     * 对象转XML
     *
     * @param object
     * @return
     */
    public static String convertToXml(Object object) {
        return convertToXml(object, DEFAULT_CHARSET);
    }

    private static String convertToXml(Object object, String charset) {
        try {
            JAXBContext context = JAXBContext.newInstance(object.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, charset);
            StringWriter stringWriter = new StringWriter();
            marshaller.marshal(object, stringWriter);
            return stringWriter.toString();
        } catch (JAXBException e) {
            logger.error("XmlUtil.convertToXml对象转换XML异常信息:" + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * xml转换成对象
     *
     * @param clazz
     * @param xmlStr
     * @param <T>
     * @return
     */
    public static <T> T coverToObject(Class<T> clazz, String xmlStr) {
        JAXBContext context = null;
        try {
            context = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            StringReader reader = new StringReader(xmlStr);
            return (T) unmarshaller.unmarshal(reader);
        } catch (JAXBException e) {
            logger.error("XmlUtil.convertToXmlXML转换对象异常信息:" + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

}
